{% extends "admin/base.html" %}
{% set active_page = 'users' %}

{% block title %}用户详情{% endblock %}

{% block page_title %}用户详情{% endblock %}

{% block page_subtitle %}查看用户基本信息、会员状态和测评记录{% endblock %}

{% block content %}
<div class="container-fluid">
    <!-- 用户基本信息 -->
    <div class="row mb-4">
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-person me-2"></i>基本信息</h5>
                </div>
                <div class="card-body">
                    <table class="table table-borderless">
                        <tr>
                            <td width="30%"><strong>用户ID:</strong></td>
                            <td>{{ user.id }}</td>
                        </tr>
                        <tr>
                            <td><strong>用户名:</strong></td>
                            <td>{{ user.username }}</td>
                        </tr>
                        <tr>
                            <td><strong>邮箱:</strong></td>
                            <td>{{ user.email }}</td>
                        </tr>
                        <tr>
                            <td><strong>注册时间:</strong></td>
                            <td>{{ user.created_at.strftime('%Y-%m-%d %H:%M:%S') if user.created_at else '-' }}</td>
                        </tr>
                        <tr>
                            <td><strong>最后登录:</strong></td>
                            <td>{{ user.last_login_at.strftime('%Y-%m-%d %H:%M:%S') if user.last_login_at else '从未登录' }}</td>
                        </tr>
                        <tr>
                            <td><strong>状态:</strong></td>
                            <td>
                                {% if user.is_active %}
                                    <span class="badge bg-success">正常</span>
                                {% else %}
                                    <span class="badge bg-danger">已禁用</span>
                                {% endif %}
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>
        
        <div class="col-md-6">
            <div class="card">
                <div class="card-header">
                    <h5 class="mb-0"><i class="bi bi-star me-2"></i>会员信息</h5>
                </div>
                <div class="card-body">
                    {% if membership %}
                        <table class="table table-borderless">
                            <tr>
                                <td width="30%"><strong>会员类型:</strong></td>
                                <td>
                                    {% if membership.plan_type == 'basic' %}
                                        <span class="badge bg-secondary">基础版</span>
                                    {% elif membership.plan_type == 'professional' %}
                                        <span class="badge bg-primary">专业版</span>
                                    {% elif membership.plan_type == 'institution' %}
                                        <span class="badge bg-success">机构版</span>
                                    {% elif membership.plan_type == 'research' %}
                                        <span class="badge bg-info">科研版</span>
                                    {% endif %}
                                </td>
                            </tr>
                            <tr>
                                <td><strong>开始时间:</strong></td>
                                <td>{{ membership.start_date.strftime('%Y-%m-%d') if membership.start_date else '-' }}</td>
                            </tr>
                            <tr>
                                <td><strong>到期时间:</strong></td>
                                <td>{{ membership.end_date.strftime('%Y-%m-%d') if membership.end_date else '-' }}</td>
                            </tr>
                            <tr>
                                <td><strong>支付金额:</strong></td>
                                <td>¥{{ membership.payment_amount or 0 }}</td>
                            </tr>
                            <tr>
                                <td><strong>状态:</strong></td>
                                <td>
                                    {% if membership.status == 'active' %}
                                        <span class="badge bg-success">有效</span>
                                    {% elif membership.status == 'expired' %}
                                        <span class="badge bg-danger">已过期</span>
                                    {% elif membership.status == 'cancelled' %}
                                        <span class="badge bg-secondary">已取消</span>
                                    {% endif %}
                                </td>
                            </tr>
                        </table>
                    {% else %}
                        <p class="text-muted">该用户暂无会员信息</p>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>
    
    <!-- 最近测评记录 -->
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0"><i class="bi bi-file-text me-2"></i>最近测评记录</h5>
            <a href="/admin-assessments?user_id={{ user.id }}" class="btn btn-outline-primary btn-sm">
                查看全部记录
            </a>
        </div>
        <div class="card-body">
            {% if recent_assessments %}
                <div class="table-responsive">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>测评ID</th>
                                <th>量表名称</th>
                                <th>状态</th>
                                <th>进度</th>
                                <th>开始时间</th>
                                <th>完成时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            {% for assessment in recent_assessments %}
                            <tr>
                                <td>{{ assessment.id }}</td>
                                <td>{{ assessment.scale.title if assessment.scale else '-' }}</td>
                                <td>
                                    {% if assessment.status.value == 'completed' %}
                                        <span class="badge bg-success">已完成</span>
                                    {% elif assessment.status.value == 'in_progress' %}
                                        <span class="badge bg-warning">进行中</span>
                                    {% elif assessment.status.value == 'abandoned' %}
                                        <span class="badge bg-secondary">已放弃</span>
                                    {% endif %}
                                </td>
                                <td>
                                    <div class="progress" style="width: 80px; height: 20px;">
                                        <div class="progress-bar" role="progressbar" 
                                             style="width: {{ (assessment.progress_percentage or 0) }}%"
                                             aria-valuenow="{{ (assessment.progress_percentage or 0) }}" 
                                             aria-valuemin="0" aria-valuemax="100">
                                            {{ (assessment.progress_percentage or 0)|round|int }}%
                                        </div>
                                    </div>
                                </td>
                                <td>{{ assessment.started_at.strftime('%Y-%m-%d %H:%M') if assessment.started_at else '-' }}</td>
                                <td>{{ assessment.completed_at.strftime('%Y-%m-%d %H:%M') if assessment.completed_at else '-' }}</td>
                                <td>
                                    <a href="/admin-assessments" class="btn btn-outline-primary btn-sm" 
                                       onclick="viewAssessmentDetail({{ assessment.id }})">
                                        查看详情
                                    </a>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>
            {% else %}
                <p class="text-muted text-center py-4">该用户暂无测评记录</p>
            {% endif %}
        </div>
    </div>
    
    <!-- 操作按钮 -->
    <div class="mt-4">
        <a href="/admin-users" class="btn btn-secondary">
            <i class="bi bi-arrow-left me-1"></i>返回用户列表
        </a>
        {% if user.is_active %}
            <button class="btn btn-warning ms-2" onclick="toggleUserStatus({{ user.id }}, false)">
                <i class="bi bi-ban me-1"></i>禁用用户
            </button>
        {% else %}
            <button class="btn btn-success ms-2" onclick="toggleUserStatus({{ user.id }}, true)">
                <i class="bi bi-check-circle me-1"></i>启用用户
            </button>
        {% endif %}
        <button class="btn btn-info ms-2" onclick="resetUserPassword({{ user.id }})">
            <i class="bi bi-key me-1"></i>重置密码
        </button>
    </div>
</div>

<script>
function toggleUserStatus(userId, enable) {
    const action = enable ? '启用' : '禁用';
    if (confirm(`确定要${action}该用户吗？`)) {
        fetch(`/api/admin/users/${userId}/toggle-status`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
            },
            body: JSON.stringify({ is_active: enable })
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert(`${action}成功`);
                location.reload();
            } else {
                alert(`${action}失败: ` + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert(`${action}失败`);
        });
    }
}

function resetUserPassword(userId) {
    if (confirm('确定要重置该用户的密码吗？新密码将发送到用户邮箱。')) {
        fetch(`/api/admin/users/${userId}/reset-password`, {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + localStorage.getItem('adminToken')
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert('密码重置成功，新密码已发送到用户邮箱');
            } else {
                alert('密码重置失败: ' + data.message);
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('密码重置失败');
        });
    }
}
</script>
{% endblock %}